﻿using HttpWebApiTest.Common;
using HttpWebApiTest.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HttpWebApiTest.MyApi
{
    /// <summary>
    /// 方式3：类型化的使用方式可以预先把配置放到自定义的 HttpClient 中，然后在需要的地方都过依赖注入直接拿到 HttpClient 实例。
    /// </summary>
    public class HttpClientMyApi
    {
        HttpClient client;
        IHttpClientFactory httpClientFactory;
        public HttpClient Client => client;

        /// <summary>
        /// 构造函数，注入IHttpClientFactory
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public HttpClientMyApi(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;

            //创建HttpClient
            client = httpClientFactory.CreateClient();

            //配置HttpClient
            //请求的根地址
            client.BaseAddress = new Uri("http://localhost:5000");
            //设置请求头信息
            //客户端类别
            client.DefaultRequestHeaders.Add(Consts.HeaderUserAgent, "HttpClientFactory-Sample");
            //JWT认证信息
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Consts.AuthorizationBearer, "jwt token");
            //自定义的 客户端ID
            client.DefaultRequestHeaders.Add("AppID", "MyApp");
        }

        /// <summary>
        /// 封装远程服务器 的Get 方法
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetInfoRemoteAsync()
        {
            var url = "/api/user/yus/12";
            return await client.GetStringAsync(url);
        }

        /// <summary>
        /// 封装远程服务器 的Post 方法
        /// </summary>
        /// <returns></returns>
        public async Task<HttpResponseMessage> SetInfoRemoteAsync(InputMode postData)
        {
            var url = "/api/setuser";
            return await client.PostAsync(url, new JsonContent(postData));
        }
    }
}
